package com.hsj.designpartten.builder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * builder模式
 * @Description:TODO
 * @author:hsj qq:2356899074
 * @time:2017年10月9日 上午9:52:50
 */
public class BuilderTest { 
	/**
	 * 日志记录
	 */ 
	 private static final Logger LOGGER = LoggerFactory.getLogger(BuilderTest.class);
	
    private final int servingSize;  
    private final int servings;  
    private final int calories;  
    private final int fat;  
    private final int sodium;  
    private final int carbohydrate;  
  
    /**
     * builder模式的内部类
     * 可以访问外部的类的所有成员域字段
     * @Description:TODO
     * @author:hsj qq:2356899074
     * @time:2017年10月9日 上午9:53:50
     */
    public static class Builder{  
        //必须注入的参数，可不用初始化  
        private final int servingSize;  
        private final int servings;  
          
        //可选择注入的参数  
        private int calories = 0;  
        private int fat = 0;  
        private int sodium = 0;  
        private int carbohydrate = 0;  
          
        //builder类构造方法  
        public Builder(int servingSize,int servings){  
            this.servingSize = servingSize;  
            this.servings = servings;  
        }  
          
        public Builder calories(int val){  
            calories = val;  
            return this;  
        }  
        public Builder carbohydrate(int val){  
            carbohydrate = val;  
            return this;  
        }  
        public Builder sodium(int val){  
            sodium = val;  
            return this;  
        }  
          
        //将当前对象传入外部内的私有构造方法中  
        public BuilderTest build(){  
            return new BuilderTest(this);  
        }  
    }  
      
    //私有构造方法  
    private BuilderTest(Builder builder){  
        servingSize = builder.servingSize;  
        servings = builder.servings;  
        calories = builder.calories;  
        fat = builder.fat;  
        sodium = builder.sodium;  
        carbohydrate = builder.carbohydrate;  
    }  
      
    @Override  
    public String toString() {  
        return "NutritionFacts [calories=" + calories + ", carbohydrate="  
                + carbohydrate + ", fat=" + fat + ", servingSize="  
                + servingSize + ", servings=" + servings + ", sodium=" + sodium  
                + "]";  
    }  
      
    public static void main(String[] args) {  
    	BuilderTest bt = new BuilderTest.Builder(8, 20).calories(2).sodium(27).build();  
    	LOGGER.info(bt.toString());  
    }  
}  

